import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Card,
  Form,
  Row,
  Col,
  Image,
  InputNumber,
  Select,
  Button,
  Typography,
  Spin,
  message,
  Checkbox
} from 'antd';
import axios from 'axios';

const { Option } = Select;
const { Title, Text } = Typography;

interface Question {
  type: string;
  content: string;
  options?: string[] | null;
  answer: string | string[] | null;
  difficulty: string;
  language?: string[] | null;
  tempId?: number;
}

const AIQuestion: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [generatedQuestions, setGeneratedQuestions] = useState<Question[] | null>(null);
  const [loading, setLoading] = useState(false);
  const [addingLoading, setAddingLoading] = useState(false);
  const [selectedQuestionsIds, setSelectedQuestionsIds] = useState<number[]>([]);

  const onFinish = async (values: any) => {
    console.log('Received values of form: ', values);
    setLoading(true);
    setGeneratedQuestions(null);
    setSelectedQuestionsIds([]);

    try {
      const response = await axios.post('/api/generate-questions', values);
      console.log('AI generation response:', response.data);

      if (response.data.code === 0) {
        const questionsWithIds = response.data.data.map((q: Question, index: number) => ({ ...q, tempId: index }));
        setGeneratedQuestions(questionsWithIds);
        message.success('题目生成成功');
      } else {
        message.error(response.data.message || '题目生成失败');
      }
    } catch (error) {
      console.error('Error calling AI generation API:', error);
      message.error('调用AI接口失败');
    } finally {
      setLoading(false);
    }
  };

  const handleQuestionSelect = (tempId: number, checked: boolean) => {
    if (checked) {
      setSelectedQuestionsIds([...selectedQuestionsIds, tempId]);
    } else {
      setSelectedQuestionsIds(selectedQuestionsIds.filter(id => id !== tempId));
    }
  };

  const handleAddSelected = async () => {
    if (selectedQuestionsIds.length === 0) {
      message.warning('请先选择要添加的题目');
      return;
    }

    setAddingLoading(true);

    const selectedQuestions = generatedQuestions?.filter(q => selectedQuestionsIds.includes(q.tempId!)) || [];

    try {
      for (const question of selectedQuestions) {
        const answer = question.type==='多选题'?JSON.stringify(question.answer):question.answer
        const submitData = {
          type: question.type,
          content: question.content,
          options: question.options ? JSON.stringify(question.options) : null,
          answer: answer,
          difficulty: question.difficulty || 'medium',
          language: (Array.isArray(question.language) ? question.language : []).join(',') || question.language
        };

        console.log('Adding question:', submitData);
        const response = await axios.post('/api/questions', submitData);

        if (response.data.code !== 0) {
          console.error('Failed to add question:', question.content, response.data.message);
          message.error(`添加题目失败: ${question.content} - ${response.data.message}`);
        }
      }
      message.success(`成功添加了 ${selectedQuestions.length} 道题目`);
      setSelectedQuestionsIds([]);
      setGeneratedQuestions(null);
      navigate('/question-bank');

    } catch (error) {
      console.error('Error adding questions:', error);
      message.error('添加题目失败');
    } finally {
      setAddingLoading(false);
    }
  };

  return (
    <Form form={form} name="ai_question" onFinish={onFinish} style={{ height: '100%',backgroundColor:'#f5f5f5',paddingTop: 8,paddingBottom:4 ,borderRadius:2}}>
      <Row gutter={24} style={{ height: '100%' ,margin:10,marginRight:5}}>
        {/* 左侧表单区域 */}
        <Col span={9} style={{ marginRight: 20 }}>
          <Card
            title={ 
              <div style={{display: 'flex', alignItems: 'center',justifyContent:'start'}}>
                <Image
                preview={false}
                src='../../favicon.ico'
                style={{height: 24, width: 24,marginRight: 10}}
                />
                <span>AI 生成试题</span>
              </div>
            }
            style={{ marginRight: 0, marginLeft: 0, borderRadius: 0, height: '100%',borderBottom: 0 }}
          >
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  label="题型"
                  name="type"
                  rules={[{ required: true, message: '请选择题目类型' }]}
                >
                  <Select placeholder="请选择">
                    <Option value="single">单选题</Option>
                    <Option value="multi">多选题</Option>
                    <Option value="code">编程题</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="题目数量"
                  name="count"
                  rules={[{ required: true, message: '请输入题目数量' }]}
                  initialValue={3}
                >
                  <InputNumber min={1} max={10} style={{ width: '100%' }} />
                </Form.Item>
              </Col>
            </Row>
            <Form.Item label="语言" name="language">
              <Select mode="multiple" placeholder="请选择">
                <Option value="go">go语言</Option>
                <Option value="js">js语言</Option>
              </Select>
            </Form.Item>

            <Form.Item>
              <div style={{ display: 'flex', justifyContent: 'center' ,marginTop: '20px' }}>
                <Button
                  type="primary"
                  htmlType="submit"
                  style={{ marginRight: 8 }}
                  loading={loading}
                >
                  生成并预览题库
                </Button>
                {generatedQuestions && generatedQuestions.length > 0 && (
                  <Button type="default" onClick={handleAddSelected} loading={addingLoading}>
                    添加到数据库
                  </Button>
                )}
              </div>
            </Form.Item>
          </Card>
        </Col>

        {/* 右侧AI生成区域 */}
        <Col span={14} style={{ padding: 8, background: '#fff' }}>
          <div
            style={{
              margin: '12px',
              border: '2px dashed #e6e6e6',
              minHeight: '400px',
              height: 'calc(100% - 24px)',
              textAlign: generatedQuestions ? 'left' : 'center',
              display: 'flex',
              flexDirection: generatedQuestions ? 'column' : 'row',
              alignItems: generatedQuestions ? 'flex-start' : 'center',
              justifyContent: generatedQuestions ? 'flex-start' : 'center',
              color: generatedQuestions ? '#333' : '',
              overflowY: 'auto'
            }}
          >
            <Spin spinning={loading} tip="AI 正在生成题目...">
              {generatedQuestions && generatedQuestions.length > 0 ? (
                generatedQuestions.map((q, index) => (
                  <div key={q.tempId} style={{ marginBottom: '20px', borderBottom: '1px dashed #eee', paddingBottom: '15px' }}>
                     <Checkbox
                       checked={selectedQuestionsIds.includes(q.tempId!)}
                       onChange={(e) => handleQuestionSelect(q.tempId!, e.target.checked)}
                       style={{ marginRight: '10px' }}
                     />
                    <Title level={5} style={{display: 'inline'}}>
                      {index + 1}. {q.content}
                    </Title>
                    {q.options && Array.isArray(q.options) && q.options.length > 0 && (
                      <ul style={{ listStyleType: 'none', paddingLeft: 5 }}>
                        {q.options.map((option, i) => (
                          <li key={i}>
                            {String.fromCharCode(65 + i)}. {option}
                          </li>
                        ))}
                      </ul>
                    )}
                    {q.type === '编程题' && q.answer && typeof q.answer === 'string' && (
                      <div>
                        <Text strong>参考答案:</Text>
                        <pre style={{ backgroundColor: '#f0f0f0', padding: '10px' }}>{q.answer}</pre>
                      </div>
                    )}
                    {q.type !== '编程题' && q.answer !== undefined && q.answer !== null && (
                      <Text strong>
                        答案: {Array.isArray(q.answer) ? q.answer.join(', ') : q.answer}
                      </Text>
                    )}
                  </div>
                ))
              ) : (
                <span style={{ fontSize: 38, color: '#e6e6e6', fontWeight: 500 }}>AI 生成区域</span>
              )}
            </Spin>
          </div>
        </Col>
      </Row>
    </Form>
  );
};

export default AIQuestion;
